import { Injectable, Query } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { promises as fs } from 'fs';
import { Like, Repository } from 'typeorm';
import { QueryFileDto } from './dto/query-file.dto';
import { UpdateFileDto } from './dto/update-file.dto';
import { File } from './entities/files.entity';

@Injectable()
export class FilesService {
  private readonly uploadPath = 'uploads';

  constructor(
    @InjectRepository(File)
    private fileRepository: Repository<File>,
  ) {
    // 确保上传目录存在
    this.initStorage();
  }

  private async initStorage() {
    try {
      await fs.mkdir(this.uploadPath, { recursive: true });
    } catch (error) {
      console.error('初始化存储失败', error);
    }
  }

  // 创建文件（直接存入数据库，不通过上传）
  async create(file){
    const type = file.originalname.endsWith('.d.ts') ? 'types' : 'components';
    const name = this.extractPrefix(file.originalname);

    // 检查是否已存在同名文件
    const existingFile = await this.findByFilename(file.originalname);

    if (existingFile) {
      // 文件已存在，更新内容
      await this.fileRepository.update(existingFile.id, {
        content: file.content,
        size: file.size,
        name,
        type
      });
      const updatedFile = await this.findOne(existingFile.id);
      return updatedFile || existingFile; // 如果 findOne 返回 null，则返回原始 existingFile
    }

    // 文件不存在，创建新文件
    const files = this.fileRepository.create({
      filename: file.originalname,
      name,
      type,
      size: file.size,
      content: file.content,
    });
    return await this.fileRepository.save(files);
  }

  // 按条件分页查询
  async findAll(query: QueryFileDto) {
    const { pageNum = 1, pageSize = 10, onlyFolder, ...rest } = query;

    const whereCondition: any = { ...rest };

    // 如果需要只查询文件夹
    if (onlyFolder !== undefined) {
      whereCondition.isFolder = onlyFolder;
    }

    const [result, total] = await this.fileRepository.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      where: whereCondition,
      order: {
        createdAt: 'DESC'
      }
    });

    return {
      rows: result,
      total
    };
  }

  // 获取types文件夹下的所有文件
  async getTypeFiles() {
    const files = await this.fileRepository.find({
      where: {
        type: Like('types%')
      },
      order: {
        createdAt: 'DESC'
      }
    });
    return files;
  }

  // 获取components文件夹下的所有文件
  async getComponentFiles() {
    const files = await this.fileRepository.find({
      where: {
        type: Like('components%')
      },
      order: {
        createdAt: 'DESC'
      }
    });
    return files;
  }

  // 按ID查询
  async findOne(id: number) {
    return this.fileRepository.findOne({
      where: { id }
    });
  }

  // 按文件名查询
  async findByFilename(filename: string) {
    return this.fileRepository.findOne({
      where: { filename }
    });
  }

  // 更新文件
  async update(id: number, updateFileDto: UpdateFileDto) {
    return this.fileRepository.update(id, updateFileDto);
  }

  // 删除文件
  async remove(id: number) {
    return this.fileRepository.delete(id);
  }
  // 提取文件名前缀
  private extractPrefix(str: string) {
    const match = str.match(/^(.+?)(?=-rules|\.)/);
    return match ? match[1] : str;
  }
} 